// src/ai/polish-queue.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../../user/entity/user.entity';
import { AiService } from './ai.service';
import {
  PolishMessageDto,
  PolishMessageResponseDto,
} from '../dto/polish-message.dto';

interface PendingRequest {
  resolve: (value: PolishMessageResponseDto) => void;
  reject: (reason: any) => void;
  timestamp: number;
}

@Injectable()
export class PolishQueueService {
  private readonly logger = new Logger(PolishQueueService.name);
  private readonly pendingRequests = new Map<string, PendingRequest>();
  private readonly requestQueue: Array<{
    requestId: string;
    data: PolishMessageDto;
  }> = [];
  private isProcessing = false;
  private readonly MAX_CONCURRENT_REQUESTS = 3;
  private readonly REQUEST_TIMEOUT = 30000; // 30秒超时
  private activeRequests = 0;

  constructor(
    private readonly aiService: AiService,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {
    // 清理过期请求的定时任务
    setInterval(() => this.cleanupExpiredRequests(), 60000);
  }

  async addPolishRequest(
    data: PolishMessageDto,
  ): Promise<PolishMessageResponseDto> {
    const requestId = data.requestId || this.generateRequestId();

    return new Promise((resolve, reject) => {
      // 设置超时
      const timeoutId = setTimeout(() => {
        this.pendingRequests.delete(requestId);
        reject(new Error('请求超时'));
      }, this.REQUEST_TIMEOUT);

      this.pendingRequests.set(requestId, {
        resolve: value => {
          clearTimeout(timeoutId);
          resolve(value);
        },
        reject: reason => {
          clearTimeout(timeoutId);
          reject(reason);
        },
        timestamp: Date.now(),
      });

      this.requestQueue.push({ requestId, data });
      this.processQueue();
    });
  }

  private async processQueue(): Promise<void> {
    if (this.isProcessing || this.requestQueue.length === 0) {
      return;
    }

    this.isProcessing = true;

    while (
      this.requestQueue.length > 0 &&
      this.activeRequests < this.MAX_CONCURRENT_REQUESTS
    ) {
      const item = this.requestQueue.shift();
      if (!item) continue;

      this.activeRequests++;
      this.processRequest(item.requestId, item.data).finally(() => {
        this.activeRequests--;
        this.processQueue(); // 继续处理队列
      });
    }

    this.isProcessing = false;
  }

  private async processRequest(
    requestId: string,
    data: PolishMessageDto,
  ): Promise<void> {
    const pendingRequest = this.pendingRequests.get(requestId);
    if (!pendingRequest) {
      this.logger.warn(`请求ID ${requestId} 已过期或不存在`);
      return;
    }

    try {
      // 获取用户信息
      const [sender, receiver] = await Promise.all([
        this.userRepository.findOne({ where: { userId: data.senderId } }),
        data.chatType === 'friend'
          ? this.userRepository.findOne({ where: { userId: data.receiverId } })
          : this.getDefaultUser(), // 对于群聊，使用默认用户
      ]);

      if (!sender) {
        throw new Error('发送方用户信息不存在');
      }

      if (!receiver) {
        throw new Error('接收方用户信息不存在');
      }

      // 调用AI服务
      const result = await this.aiService.polishMessage(
        data.originalMessage,
        sender,
        receiver,
        data.chatType,
      );

      const response: PolishMessageResponseDto = {
        requestId,
        originalMessage: data.originalMessage,
        polishedMessage: result.polishedMessage,
        reasoning: result.reasoning,
        confidence: result.confidence,
      };

      pendingRequest.resolve(response);
      this.pendingRequests.delete(requestId);
    } catch (error) {
      this.logger.error(`处理润色请求失败: ${error.message}`);
      pendingRequest.reject(error);
      this.pendingRequests.delete(requestId);
    }
  }

  private async getDefaultUser(): Promise<User> {
    // 返回一个默认用户对象
    const defaultUser = new User();
    defaultUser.userId = 'default';
    defaultUser.mbti = '未知';
    defaultUser.sex = '未知';
    return defaultUser;
  }

  private generateRequestId(): string {
    return `req_${Date.now()}_${Math.random()
      .toString(36)
      .substr(2, 9)}`;
  }

  private cleanupExpiredRequests(): void {
    const now = Date.now();
    for (const [requestId, request] of this.pendingRequests.entries()) {
      if (now - request.timestamp > this.REQUEST_TIMEOUT) {
        request.reject(new Error('请求已过期'));
        this.pendingRequests.delete(requestId);
      }
    }
  }

  // 获取当前队列状态（用于监控）
  getQueueStatus() {
    return {
      pending: this.pendingRequests.size,
      queued: this.requestQueue.length,
      active: this.activeRequests,
    };
  }
}
